package com.ant.storage.service.impl;

import com.ant.storage.common.ResultCode;
import com.ant.storage.common.ResultVo;
import com.ant.storage.dto.ContractDto;
import com.ant.storage.handler.AntException;
import com.ant.storage.mapper.ApplicationRecordMapper;
import com.ant.storage.pojo.ApplicationRecord;
import com.ant.storage.pojo.UserInfo;
import com.ant.storage.service.IApplicationRecordService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletContext;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author melon
 * @since 2024-05-09
 */
@Service
public class ApplicationRecordServiceImpl extends ServiceImpl<ApplicationRecordMapper, ApplicationRecord> implements IApplicationRecordService {

    @Autowired
    public ServletContext servletContext;

    @Override
    public PageInfo<ApplicationRecord> queryList(ContractDto dto) {
        try {
            UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
            PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
            QueryWrapper<ApplicationRecord> wrapper = new QueryWrapper<>();
            wrapper.orderByDesc("id");
            List<ApplicationRecord> list = this.baseMapper.selectList(wrapper);
            PageInfo<ApplicationRecord> pageInfo = new PageInfo<>(list);
            return pageInfo;
        } catch (Exception e) {
            throw new AntException(ResultCode.BODY_NOT_MATCH);
        }
    }

    @Override
    public ApplicationRecord findApplicationRecordById(Integer id) {
        if (id == null) {
            throw new AntException(ResultCode.FAILURE.getResultCode(), "参数错误");
        } else {
            return this.baseMapper.selectOne(new QueryWrapper<ApplicationRecord>()
                    .eq("id", id));
        }
    }

    @Override
    public ResultVo applicationRecordSave(ApplicationRecord dto) {
        synchronized (this) {
            UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
            if (dto.getId() == null) {
               // dto.setc(userInfo.getCityId());
               // dto.setCompanyId(userInfo.getDepId());
                //  dto.setContractNumber("HT" + RandomUtil.getOrderNumbers(this.baseMapper.selectLastID()));
                dto.setCreateBy(userInfo.getUserName());
                dto.setCreationTime(new Date());
                this.baseMapper.insert(dto);
            } else {
                this.baseMapper.updateById(dto);
            }

            return ResultVo.success("操作成功");
        }
    }

    @Override
    public ResultVo contractUpdate(ApplicationRecord dto) {
        return null;
    }
}
